<?php
//set_time_limit(0);
$filename  = dirname(__FILE__)."/chat/";

// store new message in the file
$msg = isset($_REQUEST['msg']) ? $_REQUEST['msg'] : '';
if ($msg != '')
{
  lock_write($filename."../admin",$msg);
  die();
}
$filename.=$_COOKIE["chat_username"];
// infinite loop until the data file is not modified
$lastmodif    = isset($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
  usleep(10000); // sleep 10ms to unload the CPU
  clearstatcache();
  $currentmodif = filemtime($filename);
  touch($filename,$currentmodif,time());
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
$response['timestamp'] = $currentmodif;

echo json_encode($response);
//echo "bb";
flush();
function lock_write($file,$contents,$mode="a+")
{
	$fp = fopen($file, $mode);

	if (flock($fp, LOCK_EX)) 
	{ // 进行排它型锁定
		fwrite($fp, $contents);
		flock($fp, LOCK_UN); // 释放锁定
	}
	 else 
	 {
		//echo "Couldn't lock the file !";
	}

	fclose($fp);
}
?>